package com.tuwan.sensorcatcher

import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.*
import android.os.Environment
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import android.util.Log
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class CatcherService : Service() {
    private lateinit var savedFileName:String
    private lateinit var savedFileName1:String
    private lateinit var savedFileName2:String
    private var period:Int = 1000//us
    private val mSensorService: SensorManager  by lazy<SensorManager> {
        getSystemService(Context.SENSOR_SERVICE) as SensorManager
    }


    private lateinit var mAcceSensor:Sensor
    private lateinit var mOrientaionSensor:Sensor
    private lateinit var mGyroscope:Sensor

    private val mListener:SensorEventListener by lazy<SensorEventListener> {
        object : SensorEventListener {
            override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

            }
            var count=0;
            var sencond=0
            var buffer = StringBuffer()

            var count1=0;
            var sencond1=0
            var buffer1 = StringBuffer()

            var count2=0;
            var sencond2=0
            var buffer2 = StringBuffer()
            override fun onSensorChanged(e: SensorEvent?) {
                Log.i("test","${e!!.sensor.name},${Arrays.toString(e!!.values)}")
                when (e!!.sensor.name){
                    mAcceSensor.name ->{
                        count++
                        var s = 0
                        for( s in e!!.values){
                            buffer.append(s)
                            buffer.append(",")
                        }
                        buffer.append(format(System.currentTimeMillis()))
                        buffer.append("\n")
                        if(count * period >= 1000000){

                            //一秒一存
                            LogFileUtils.log("/ACCELEROMETER","acce_"+savedFileName,buffer.toString())
                            count = 0
                            sencond++
                            buffer.setLength(0)
                            if(sencond >= 60 * 30){
                                savedFileName = makeFileName()
                                sencond = 0
                            }
                        }
                    }
                    mOrientaionSensor.name ->{
                        count1++
                        var s = 0
                        for( s in e!!.values ){
                            buffer1.append(s)
                            buffer1.append(",")
                        }
                        buffer1.append(format(System.currentTimeMillis()))
                        buffer1.append("\n")
                        if(count1 * period >= 1000000){

                            //一秒一存
                            LogFileUtils.log("/ORIENTATION","orie_"+savedFileName1,buffer1.toString())
                            count1 = 0
                            sencond1++
                            buffer1.setLength(0)
                            if(sencond1 >= 60 * 30){
                                savedFileName1= makeFileName()
                                sencond1 = 0
                            }
                        }
                    }
                    mGyroscope.name ->{
                        count2++
                        var s = 0
                        for( s in e!!.values ){
                            buffer2.append(s)
                            buffer2.append(",")
                        }
                        buffer2.append(format(System.currentTimeMillis()))
                        buffer2.append("\n")
                        if(count2 * period >= 1000000){

                            //一秒一存
                            LogFileUtils.log("/GYROSCOPE","gyro_"+savedFileName2,buffer2.toString())
                            count2 = 0
                            sencond2++
                            buffer2.setLength(0)
                            if(sencond2 >= 60 * 30){
                                savedFileName2 = makeFileName()
                                sencond2 = 0
                            }
                        }
                    }


                }


            }
        }
    }
    private var  formatter = SimpleDateFormat("HH:mm:ss")
    private fun format(timestamp:Long):String{
       return formatter.format(timestamp)
    }



    override fun onBind(intent: Intent): IBinder? {
        // TODO: Return the communication channel to the service.
        throw UnsupportedOperationException("Not yet implemented")
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if(intent!=null){
            val sd = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED || !Environment.isExternalStorageRemovable()
            val root = if (sd) Environment.getExternalStorageDirectory().absolutePath else filesDir.absolutePath
            var savePath = File("${root}/catcher/")
            makeDir(root,"ORIENTATION")
            makeDir(root,"ACCELEROMETER")
            makeDir(root,"GYROSCOPE")
            LogFileUtils.setLogFold(savePath.absolutePath)
            LogFileUtils.setEnable(true)
            savedFileName =makeFileName()
            savedFileName1 =makeFileName()
            savedFileName2 =makeFileName()
            period = intent!!.getIntExtra("set_period",1000000)
            mAcceSensor = mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
            mOrientaionSensor= mSensorService.getDefaultSensor(Sensor.TYPE_ORIENTATION)
            mGyroscope = mSensorService.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
           // Toast.makeText(this,"周期为:"+period+" us",Toast.LENGTH_SHORT).show()
            mSensorService.registerListener(mListener, mOrientaionSensor,period)
            mSensorService.registerListener(mListener, mAcceSensor,period)
            mSensorService.registerListener(mListener, mGyroscope,period)
            useForeground("服务已开启",savePath.absolutePath+"/")

        }

        return START_STICKY
    }
    fun makeDir(root:String , dir:String){
        var savePath = File("${root}/catcher/${dir}/")
        if(!savePath.exists()){
            savePath.mkdirs()
        }
    }

    fun useForeground(tickerText: CharSequence, content: String) {
        val notificationIntent = Intent(applicationContext, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(applicationContext, 0, notificationIntent, 0)
        val mNotifyBuilder = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setTicker(tickerText)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(getString(R.string.app_name))
                .setContentText(content)
                .setContentIntent(pendingIntent)
        val notification = mNotifyBuilder.build()

        startForeground(12, notification)
    }

    fun makeFileName():String{
       return SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis())+".csv"
    }

    override fun onDestroy() {
        super.onDestroy()
        if(mSensorService!=null){
            mSensorService.unregisterListener(mListener)
        }
    }




}


